package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMsgDto;
import com.zzyl.nursing.dto.PageClass;
import com.zzyl.nursing.dto.questDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.ElderMsgVo;
import com.zzyl.nursing.vo.MemberVo;
import org.apache.ibatis.scripting.xmltags.WhereSqlNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 客户老人关联Service业务层处理
 *
 * @author alexis
 * @date 2024-11-18
 */
@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements IFamilyMemberElderService {
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private RoomMapper roomMapper;


    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    /**
     * 查询客户老人关联
     *
     * @param id 客户老人关联主键
     * @return 客户老人关联
     */
    @Override
    public FamilyMemberElder selectFamilyMemberElderById(Long id) {
        return getById(id);
    }

    /**
     * 查询客户老人关联列表
     *
     * @param familyMemberElder 客户老人关联
     * @return 客户老人关联
     */
    @Override
    public List<FamilyMemberElder> selectFamilyMemberElderList(FamilyMemberElder familyMemberElder) {
        return familyMemberElderMapper.selectFamilyMemberElderList(familyMemberElder);
    }

    /**
     * 新增客户老人关联
     *
     * @param familyMemberElder 客户老人关联
     * @return 结果
     */
    @Override
    public int insertFamilyMemberElder(FamilyMemberElder familyMemberElder) {
        return save(familyMemberElder) ? 1 : 0;
    }

    /**
     * 修改客户老人关联
     *
     * @param familyMemberElder 客户老人关联
     * @return 结果
     */
    @Override
    public int updateFamilyMemberElder(FamilyMemberElder familyMemberElder) {
        return updateById(familyMemberElder) ? 1 : 0;
    }

    /**
     * 批量删除客户老人关联
     *
     * @param ids 需要删除的客户老人关联主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberElderByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除客户老人关联信息
     *
     * @param id 客户老人关联主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberElderById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void add(FamilyMsgDto dto) {


        Elder elder = elderMapper.selectOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getIdCardNo, dto.getIdCard()));

        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("没这个老人");
        }

        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        Long l = UserThreadLocal.get();
        familyMemberElder.setFamilyMemberId(l);
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setRemark(dto.getRemark());

        save(familyMemberElder);
    }

    @Override
    public List<MemberVo> selectAll() {

        Long l = UserThreadLocal.get();
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(Wrappers.lambdaQuery(FamilyMemberElder.class).eq(FamilyMemberElder::getFamilyMemberId, l));
        List<MemberVo> list = new ArrayList<>();
        familyMemberElders.forEach(e -> {
            Long elderId = e.getElderId();
            Elder elder = elderMapper.selectElderById(elderId);
            MemberVo memberVo = new MemberVo();
            memberVo.setElderId(elder.getId());
            memberVo.setFamilyMemberId(l);
            memberVo.setElderName(elder.getName());
            memberVo.setId(e.getId());
            list.add(memberVo);
        });

        return list;


    }

    @Override
    public List<ElderMsgVo> selectElder(PageClass pageClass) {
        Long l = UserThreadLocal.get();
        Page<FamilyMemberElder> page = new Page<>(pageClass.getPageNum(), pageClass.getPageSize());
        Page<FamilyMemberElder> page1 = page(page, (Wrappers.lambdaQuery(FamilyMemberElder.class).eq(FamilyMemberElder::getFamilyMemberId, l)));

        List<FamilyMemberElder> familyMemberElders = page1.getRecords();

        List<ElderMsgVo> list = new ArrayList<>();
        familyMemberElders.forEach(e -> {
            ElderMsgVo elderMsgVo = new ElderMsgVo();
            elderMsgVo.setMid(String.valueOf(e.getId()));
            elderMsgVo.setMremark(e.getRemark());
            elderMsgVo.setElderId(String.valueOf(e.getElderId()));
            Elder elder = elderMapper.selectOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getId, e.getElderId()));

            elderMsgVo.setImage(elder.getImage());
            elderMsgVo.setBedNumber(elder.getBedNumber());

            Bed bed = bedMapper.selectOne(Wrappers.lambdaQuery(Bed.class).eq(Bed::getId, elder.getBedId()));
            Long roomId = bed.getRoomId();

            Room room = roomMapper.selectOne(Wrappers.lambdaQuery(Room.class).eq(Room::getId, roomId));
            String typeName = room.getTypeName();


            elderMsgVo.setTypeName(typeName);
            elderMsgVo.setName(elder.getName());


            List<Device> devices = deviceMapper.selectList(Wrappers.lambdaQuery(Device.class).eq(Device::getBindingLocation, elder.getId()));

            devices.forEach(device -> {
                String iotId = device.getIotId();
                String productKey = device.getProductKey();
                elderMsgVo.setIotId(iotId);
                elderMsgVo.setProductKey(productKey);
                elderMsgVo.setDeviceName(device.getDeviceName());
            });

            list.add(elderMsgVo);


        });

        return list;


    }

    @Override
    public statusD selectDevice(questDto request) {

        String productKey = request.getProductKey();
        String deviceName = request.getDeviceName();

        QueryDevicePropertyStatusRequest queryDevicePropertyStatusRequest = new QueryDevicePropertyStatusRequest();

        queryDevicePropertyStatusRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryDevicePropertyStatusRequest.setDeviceName(deviceName);
        queryDevicePropertyStatusRequest.setProductKey(productKey);

        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(queryDevicePropertyStatusRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("调用IOT平台查询设备物模型运行状态失败");
        }

        ArrayList<PropertyStatusInfo> infos = new ArrayList<>();


        QueryDevicePropertyStatusResponseBody.QueryDevicePropertyStatusResponseBodyData data = response.getBody().getData();
        List<QueryDevicePropertyStatusResponseBody.QueryDevicePropertyStatusResponseBodyDataListPropertyStatusInfo> propertyStatusInfo = data.getList().getPropertyStatusInfo();
        propertyStatusInfo.forEach(e -> {
            PropertyStatusInfo propertyStatusInfo1 = new PropertyStatusInfo();
            propertyStatusInfo1.setTime(e.getTime());
            propertyStatusInfo1.setValue(e.getValue());
            propertyStatusInfo1.setUnit(e.getUnit());
            propertyStatusInfo1.setIdentifier(e.getIdentifier());
            propertyStatusInfo1.setName(e.getName());
            propertyStatusInfo1.setDataType(e.getDataType());

            infos.add(propertyStatusInfo1);

        });

        return new statusD(infos);


        // 获取IOT平台返回的结果，返回给前端


    }

    @Override
    public List<TimeOfData> queryDataOfTime(

            String functionId,
            Long startTime,
            Long endTime,
            String iotId
    ) {


// 将 startTime 和 endTime 转换为 LocalDateTime
        LocalDateTime startDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
        LocalDateTime endDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault());





        // 初始化数据列表
        ArrayList<TimeOfData> data = new ArrayList<>();

        // 循环获取每小时的数据
        LocalDateTime currentStartTime = startDateTime;
        while (currentStartTime.isBefore(endDateTime)) {

           LocalDateTime currentEndTime = currentStartTime.plusHours(1);

            // 将 currentStartTime 转换为字符串，去掉 T 字符，再转换回 LocalDateTime

            // 调用 Mapper 方法
            TimeOfData time1 = deviceDataMapper.selectData(currentStartTime, currentEndTime, iotId, functionId);
            data.add(time1);
            System.out.println(time1);

            // 增加一个小时
            currentStartTime = currentStartTime.plusHours(1);
        }

        System.out.println(data);

        return data;
    }

    @Override
    public List<TimeOfData> queryDataOfWeek(String functionId, Long startTime, Long endTime, String iotId) {


        LocalDateTime startDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
        LocalDateTime endDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault());

        // 初始化数据列表
        ArrayList<TimeOfData> data = new ArrayList<>();

        // 循环获取每小时的数据
        LocalDateTime currentStartTime = startDateTime;
        while (currentStartTime.isBefore(endDateTime)) {

           LocalDateTime currentEndTime = currentStartTime.plusDays(1);
            TimeOfData time1 = deviceDataMapper.selectWeek(currentStartTime, currentEndTime, iotId, functionId);
            data.add(time1);
            System.out.println(time1);

            // 增加一个小时
            currentStartTime = currentStartTime.plusDays(1);
        }

        System.out.println(data);

        return data;
    }
}
